package com.bwie.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.bwie.Dto.ProdInfoDto;
import com.bwie.domain.OrderDetail;
import com.bwie.domain.OrderRecord;
import com.bwie.domain.ProdInfo;
import com.bwie.mapper.OrderDetailMapper;
import com.bwie.mapper.OrderRecordMapper;
import com.bwie.mapper.ProdInfoMapper;
import com.bwie.utils.JwtsUtils;
import com.bwie.utils.R;
import org.apache.commons.lang3.ObjectUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.OrderMapper;
import com.bwie.domain.Order;
import com.bwie.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProdInfoMapper prodInfoMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderRecordMapper orderRecordMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedissonClient redissonClient;



    @Override
    public R saveOrderInfo(List<ProdInfoDto> prodInfoDtoList) {
        String token = request.getHeader("token");
        Integer idByToken = JwtsUtils.getIdByToken(token);
        // 1校验参数查看，购买的商品是否存在
        if(prodInfoDtoList == null || prodInfoDtoList.size() <= 0){
            return R.ERROR(-1,"请先添加商品，再下单");
        }
        BigDecimal price = BigDecimal.ZERO;
        StringJoiner joiner = new StringJoiner(",");
        // 2获取分布式锁
        RLock lock = redissonClient.getLock("save-order-lock");
        /*无限等待获取锁*/
        lock.lock();
        try {
            // 3 校验库存是否充足
            for (ProdInfoDto prodInfoDto : prodInfoDtoList) {
                // 3.1 查询剩余库存
                ProdInfo prodInfo = prodInfoMapper.selectById(prodInfoDto.getIndoId());
                if (ObjectUtils.isEmpty(prodInfo)){
                    return R.ERROR(500,"数据异常");
                }
                if (prodInfo.getProdStock().intValue() < prodInfoDto.getBuyNum()){
                    return R.ERROR(500,"商品"+prodInfoDto.getProdName()+",库存不足");
                }
            // 4 扣减库存
                prodInfo.setProdStock(prodInfo.getProdStock()-prodInfoDto.getBuyNum());
                prodInfo.setUpdateBy(idByToken);
                prodInfo.setUpdateDate(new Date());
                prodInfoMapper.updateById(prodInfo);
            }
            //  5 生成订单数据
            Order order = new Order();
            // 下单用户
            order.setUserId(idByToken);
            // 总金额
            order.setOrderAmount(price);
            // 默认未支付 0 未支付
            order.setOrderStatus(0);
            // 初始化审计字段
            order.setDeleteFlag(0);
            order.setCreateBy(idByToken);
            order.setCreateDate(new Date());
            // 订单类型
            order.setOrderType(0);
            // 商品信息
            order.setProdInfo(joiner.toString());
            //  雪花算法 生成订单编号
            order.setOrderNo(IdUtil.getSnowflake(1,1).nextIdStr());
            orderMapper.insert(order);
            // 生成订单明细

            for (ProdInfoDto infoDto : prodInfoDtoList) {
                OrderDetail orderDetail = new OrderDetail();
                //订单编号ID
                orderDetail.setOrderId(order.getOrderId().intValue());
                //商品库存ID
                orderDetail.setInfoId(infoDto.getIndoId().intValue());
                //商品ID
                orderDetail.setProdId(infoDto.getProdId().intValue());
                //购买数量
                orderDetail.setBuyNum(infoDto.getBuyNum());
                //商品价格
                orderDetail.setBuyPrice(infoDto.getProdPrice());
                //初始化审计字段
                orderDetail.setDeleteFlag(0);
                orderDetail.setCreateBy(idByToken);
                orderDetail.setCreateDate(new Date());

                orderDetailMapper.insert(orderDetail);
            }
            // 生成订单记录
            OrderRecord orderRecord = new OrderRecord();
            orderRecord.setOrderId(order.getOrderId().intValue());
            orderRecord.setOptRecord("用户创建订单");
            orderRecord.setCreateBy(idByToken);
            orderRecord.setCreateDate(new Date());
            orderRecordMapper.insert(orderRecord);
        } finally {
            // 8 释放锁
            lock.unlock();
        }

        return R.OK();
    }
}
